package com.fancon.android.gardenjokesx.activity;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.social.AccessTokenWeibo;
import com.fancon.android.gardenjokesx.social.DatabaseHelper;
import com.fancon.android.gardenjokesx.social.Keys;
import com.fancon.android.gardenjokesx.social.RequestToken;
import com.fancon.android.gardenjokesx.social.Weibo;
import com.fancon.android.gardenjokesx.social.WeiboException;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.UserUtil;

public class S03_7Activity extends GardenJokesBaseActivity {

	private WebView webView;
	private TextView s03_1_2_3_4_7_title;
	private RelativeLayout topBar;

	public static final String URL_ACTIVITY_CALLBACK = "weiboapp://callback";
	public static final String FROM = "Meshtiles";

	private int screenID;
	private Bundle bund;
	//private String isSignIn;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.s03_1_2_3_4_7);

		if (getIntent().getExtras() != null) {
			bund = getIntent().getExtras();
			screenID = bund.getInt(Constant.SCREEN_ID);
			//isSignIn = getIntent().getExtras().getString(Constant.IS_SIGNIN);
		}

		CookieSyncManager.createInstance(this);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeAllCookie();

		Weibo weibo = Weibo.getInstance();

		webView = (WebView) findViewById(R.id.s03_12347_webview);

		// set Text cho Title cua man hinh, twitter, weibo, facebook,...
		// set Backgroud cho Top Bar
		// Xu ly nut Back
		topBar = (RelativeLayout) findViewById(R.id.s03_12347_bg_top);
		s03_1_2_3_4_7_title = (TextView) findViewById(R.id.s03_12347_title);

		s03_1_2_3_4_7_title.setText(getString(R.string.s03_7_titler));
		topBar.setBackgroundResource(R.drawable.common_bg_top);

		Button s03_12347_btnDone = (Button) findViewById(R.id.s03_12347_btnDone);
		s03_12347_btnDone.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				bund.putBoolean(Constant.LINK_STATE, false);
				finishAc();
			}
		});

		// Khoi tao ket noi toi Weibo
		weibo = Weibo.getInstance();
		weibo.setupConsumerConfig(Keys.WEIBO_CONSUMER_KEY,
				Keys.WEIBO_CONSUMER_SECRET);
		try {
			RequestToken requestToken = weibo.getRequestToken(
					S03_7Activity.this, Weibo.APP_KEY, Weibo.APP_SECRET,
					URL_ACTIVITY_CALLBACK);
			String url = Weibo.URL_AUTHENTICATION
					+ "?display=wap2.0&oauth_token=" + requestToken.getToken()
					+ "&from=" + FROM;
			setUpWebView(url);
		} catch (WeiboException e) {
			e.printStackTrace();
		}
	} // End onCreate

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			bund.putBoolean(Constant.LINK_STATE, false);
			finishAc();
		}
		return (super.onKeyDown(keyCode, event));
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	private void setUpWebView(String url) {
		webView.setVerticalScrollBarEnabled(false);
		webView.setHorizontalScrollBarEnabled(false);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setAppCacheEnabled(false);
		webView.getSettings().setSavePassword(false);
		webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		webView.setWebViewClient(new MyWebViewClient());
		webView.loadUrl(url);
		webView.requestFocus();
	}

	private class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.v("Connect to Weibo", url);
			if (url.startsWith(URL_ACTIVITY_CALLBACK)) {
				Weibo weibo = Weibo.getInstance();
				String oauth_verifier = getVerifier(url);
				Log.v("oauth_verifier", oauth_verifier);
				weibo.addOauthverifier(oauth_verifier);
				try {
					weibo.generateAccessToken(S03_7Activity.this, null);
				} catch (WeiboException e1) {
					e1.printStackTrace();
				}
				String mAccessToken = weibo.getAccessToken().getToken();
				String mTokenSecret = weibo.getAccessToken().getSecret();

				Log.d("WEIBO TOKEN", "Token: " + mAccessToken + "; Secret: "
						+ mTokenSecret);
				AccessTokenWeibo accessToken = new AccessTokenWeibo(
						mAccessToken, mTokenSecret);
				weibo.setAccessToken(accessToken);

				User userID = new User();
				userID = UserUtil.getInfoUserLogin(S03_7Activity.this);
				try {
					DatabaseHelper db = new DatabaseHelper(
							S03_7Activity.this.getApplicationContext());
					db.addWeiboUser(userID.getUser_id(), weibo.getAccessToken()
							.getToken(), weibo.getAccessToken().getSecret(),
							"WeiboService", weibo.getAccessToken()
									.getVerifier(), "username");
					db.close();
				} catch (Exception e) {
					e.printStackTrace();
					// TODO: handle exception
				}
				bund.putBoolean(Constant.LINK_STATE, true);
				finishAc();

			} else {
				view.loadUrl(url);
			}

			return true;
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			Log.v("Page error", description);
			super.onReceivedError(view, errorCode, description, failingUrl);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			ClearCacheWebview();
		}

	}

	private String getVerifier(String callbackUrl) {
		String verifier = "";

		try {
			callbackUrl = callbackUrl.replace("weiboapp", "http");

			URL url = new URL(callbackUrl);
			String query = url.getQuery();

			String array[] = query.split("&");

			for (String parameter : array) {
				String v[] = parameter.split("=");

				if (URLDecoder.decode(v[0]).equals(
						oauth.signpost.OAuth.OAUTH_VERIFIER)) {
					verifier = URLDecoder.decode(v[1]);
					break;
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		return verifier;
	}

	public void ClearCacheWebview() {
		S03_7Activity.this.deleteDatabase("webview.db");
		S03_7Activity.this.deleteDatabase("webviewCache.db");
		webView.clearHistory();
		webView.clearFormData();
		webView.clearCache(true);
		Log.v("Clear cache webview", "Clear success");
	}

	public void finishAc() {
		ClearCacheWebview();

		switch (screenID) {
		case Constant.S03:
			// @binhbt comment
			/*
			 * Intent ii = new
			 * Intent(S03_7Activity.this.getApplicationContext(),
			 * S03Activity.class); ii.putExtra(Constant.IS_SIGNIN, isSignIn);
			 * startActivity(ii); finish();
			 */
			break;

		case Constant.M01_1:
			Intent inten = getIntent();
			inten.putExtras(bund);
			setResult(RESULT_OK, inten);
			finish();
			break;

		case Constant.P06:
			Intent in = getIntent();
			in.putExtras(bund);
			setResult(RESULT_OK, in);
			finish();
			break;

		case Constant.M04_7:
			Intent intent = getIntent();
			intent.putExtras(bund);
			setResult(RESULT_OK, intent);
			finish();
			break;

		case Constant.S07:
			// @binhbt comment
			/*
			 * Intent inn = new Intent(S03_7Activity.this, S07Activity.class);
			 * inn.putExtras(bund); startActivity(inn); finish();
			 */
			break;

		default:
			finish();
			break;
		}
	}

}
